package com.ruoyi.flowable.listener.repair;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquRepair;
import com.ruoyi.equ.service.IEquRepairService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 维修3-执行监听
 */
@Slf4j
@Component("repairExecutionListener")
public class RepairExecutionListener implements ExecutionListener {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final IEquRepairService repairService = SpringUtils.getBean(IEquRepairService.class);

    @Override
    public void notify(DelegateExecution execution) {
        try {
            //维修执行信息
            //派工部门+负责人+故障位置+原因+措施+部件清单+维修时长，如“设备科+李四+主板接口+接触不良+清洁校准+无+2小时”
            String wrongLocation = execution.getVariable("wrongLocation", String.class);
            String firstConfirm = execution.getVariable("firstConfirm", String.class);
            List<String> wrongReason = (List<String>) execution.getVariable("wrongReason");
            List<String> repairStep = (List<String>) execution.getVariable("repairStep");
            //TODO 补充部件
            List<Map<String, Object>> materialSubForm = (List<Map<String, Object>>) execution.getVariable("materialSubForm");
            List<Map<String, Object>> parts = new ArrayList<>();
            materialSubForm.forEach(item -> {
                HashMap<String, Object> data = new HashMap<>();
                data.put("材料/部件名称", item.get("materialName"));
                data.put("型号规格", item.get("modelSpec"));
                data.put("数量", item.get("quantity"));
                data.put("单价", item.get("unitPrice"));
                data.put("金额", item.get("amount"));
                data.put("供应商", item.get("supplier"));
                parts.add(data);
            });
            List<String> repairDuration = (List<String>) execution.getVariable("repairTime");
            String repairTime = getRepairTime(repairDuration);
            String allAmount = execution.getVariable("allAmount", String.class);

            EquRepair equRepair = execution.getVariable("equRepair", EquRepair.class);

            Map<String, Object> repairExecMap = objectMapper.readValue(equRepair.getRepairExec(), new TypeReference<Map<String, Object>>() {});
            repairExecMap.put("故障位置", wrongLocation);
            repairExecMap.put("初步判断", firstConfirm);
            repairExecMap.put("故障原因", wrongReason);
            repairExecMap.put("维修措施", repairStep);//维修内容
            repairExecMap.put("部件清单", parts);
            repairExecMap.put("维修时长", repairTime);
            repairExecMap.put("维修费用", allAmount);//维修金额
            String repairExec = objectMapper.writeValueAsString(repairExecMap);

            //工单最终状态
            String orderStatus = "维修中";

            //updateBy
            String updateBy = SecurityUtils.getLoginUser().getUser().getNickName();

            equRepair.setRepairExec(repairExec);
            equRepair.setOrderStatus(orderStatus);
            equRepair.setUpdateBy(updateBy);

            //修改
            repairService.updateEquRepair(equRepair);
            //json
            execution.setVariable("equRepair", equRepair);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    //解析维修时间间隔
    public static String getRepairTime(List<String> repairDuration) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time1 = LocalDateTime.parse(repairDuration.get(0), formatter);
        LocalDateTime time2 = LocalDateTime.parse(repairDuration.get(1), formatter);
        Duration duration = Duration.between(time1, time2);
        long days = duration.toDays();
        long hours = duration.toHours() % 24;
        if (hours == 0) {
            return days + "天";
        } else {
            return days + "天" + hours + "小时";
        }
    }
}
